<template>
  <CollapseContainer
    :title="t('routes.dashboard.account.setting.secureSetting.title')"
    :canExpand="false"
  >
    <List>
      <ListItem>
        <template #actions>
          <a>
            <Authority :value="'Root.Identity.ChangePassword'">
              <Button type="link" size="small" @click="handleModify('password')">
                {{ t('routes.dashboard.account.setting.modifyText') }}
              </Button>
            </Authority>
          </a>
        </template>
        <ListItemMeta>
          <template #title>
            {{ t('routes.dashboard.account.setting.secureSetting.password') }}
          </template>
          <template #description>
            <div>
              {{ t('routes.dashboard.account.setting.secureSetting.passwordDescription') }}
            </div>
          </template>
        </ListItemMeta>
      </ListItem>
      <ListItem>
        <template #actions>
          <a v-if="userInfo.Email">
            <Button type="link" size="small" @click="handleRemove('email')">
              {{ t('routes.dashboard.account.setting.unbindText') }}
            </Button>
          </a>
          <a>
            <Button type="link" size="small" @click="handleModify('email')">
              {{ t('routes.dashboard.account.setting.bindText') }}
            </Button>
          </a>
        </template>
        <ListItemMeta>
          <template #title>
            {{ t('routes.dashboard.account.setting.email') }}
          </template>
          <template #description>
            <div>
              {{
                t('routes.dashboard.account.setting.secureSetting.emailDescription', [
                  userInfo.Email,
                ])
              }}
            </div>
          </template>
        </ListItemMeta>
      </ListItem>
      <ListItem>
        <template #actions>
          <a v-if="userInfo.PhoneNumber">
            <Button type="link" size="small" @click="handleRemove('mobile')">
              {{ t('routes.dashboard.account.setting.unbindText') }}
            </Button>
          </a>
          <a>
            <Button type="link" size="small" @click="handleModify('mobile')">
              {{ t('routes.dashboard.account.setting.bindText') }}
            </Button>
          </a>
        </template>
        <ListItemMeta>
          <template #title>
            {{ t('routes.dashboard.account.setting.mobile') }}
          </template>
          <template #description>
            <div>
              {{
                t('routes.dashboard.account.setting.secureSetting.mobileDescription', [
                  userInfo.PhoneNumber,
                ])
              }}
            </div>
          </template>
        </ListItemMeta>
      </ListItem>
    </List>
    <ChangePasswordModal
      @register="registerChangePasswordModal"
      :sendTitle="t('routes.dashboard.account.setting.modifyPassword')"
      :beforeOkFunc="handleChangePasswordModalOk"
    />
    <ChangeEmailModal
      @register="registerChangeEmailModal"
      :sendTitle="t('routes.dashboard.account.setting.modifyEmail')"
      :checkEmailExist="true"
      :beforeOkFunc="handleChangeEmailModalOk"
    />
    <ChangePhoneModal
      @register="registerChangePhoneModal"
      :sendTitle="t('routes.dashboard.account.setting.modifyMobile')"
      :checkMobileExist="true"
      :beforeOkFunc="handleChangePhoneModalOk"
    />
  </CollapseContainer>
</template>
<script lang="ts" setup>
  import { List, Button } from 'ant-design-vue';
  import { onMounted, ref, h } from 'vue';
  import { CollapseContainer } from '@/components/Container/index';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';

  import { useIdentityStore } from '@/store/modules/identity';

  import { Authority } from '@/components/Authority';
  import { useModal } from '@/components/AdVxeModal';
  import { ChangePasswordModal, SendEmailModal, SendSMSModal } from '@/components/ViewModal';

  const ListItem = List.Item;
  const ListItemMeta = List.Item.Meta;
  const ChangeEmailModal = SendEmailModal;
  const ChangePhoneModal = SendSMSModal;

  const { t } = useI18n();
  const identityStore = useIdentityStore();
  const userInfo = ref(identityStore.getUserInfo);
  const { createMessage, createConfirm, createSuccessModal } = useMessage();
  const [registerChangePasswordModal, { openModal: openChangePasswordModal }] = useModal();
  const [registerChangeEmailModal, { openModal: openChangeEmailModal }] = useModal();
  const [registerChangePhoneModal, { openModal: openChangePhoneModal }] = useModal();

  onMounted(async () => {
    userInfo.value = identityStore.getUserInfo;
  });

  /** 处理移除 */
  async function handleRemove(key: 'email' | 'mobile') {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', t('common.warmReminderText')),
      content: () =>
        h(
          'span',
          key === 'email'
            ? t('routes.dashboard.account.setting.confirmUnbindText', [userInfo.value.Email])
            : t('routes.dashboard.account.setting.confirmUnbindText', [userInfo.value.PhoneNumber]),
        ),
      onOk: async () => {
        const userInfoInput = {
          Id: userInfo.value.UserId,
          UserName: userInfo.value.UserName,
          NickName: userInfo.value.NickName,
          Email: userInfo.value.Email,
          PhoneNumber: userInfo.value.PhoneNumber,

          Avatar: userInfo.value.Avatar,
          Signature: userInfo.value.Signature,

          Gender: userInfo.value.Gender,
          Birthday: userInfo.value.Birthday,
          BloodType: userInfo.value.BloodType,
          Tag: userInfo.value.Tag,
          Title: userInfo.value.Title,
          Address: userInfo.value.Address,
          Profile: userInfo.value.Profile,
          Sign: userInfo.value.Sign,

          Remark: userInfo.value.Remark,

          HomePath: userInfo.value.HomePath,
        };

        switch (key) {
          case 'email':
            userInfoInput.Email = '';
            break;
          case 'mobile':
            userInfoInput.PhoneNumber = '';
            break;
        }
        const userInfoValue = await identityStore.profileEdit(userInfoInput);
        if (userInfoValue !== undefined && userInfoValue !== null) {
          userInfo.value = userInfoValue;
          createMessage.success(t('routes.dashboard.account.setting.submitSuccess'));
        }
      },
    });
  }

  /** 处理修改 */
  function handleModify(key: 'password' | 'email' | 'mobile') {
    switch (key) {
      case 'password':
        openChangePasswordModal(true, {
          userId: userInfo.value.UserId,
        });
        break;
      case 'email':
        openChangeEmailModal(true, {
          userId: userInfo.value.UserId,
          email: userInfo.value.Email,
          emailConfirmUrl: `${window.location.origin}/#/confirm-email`,
        });
        break;
      case 'mobile':
        openChangePhoneModal(true, {
          userId: userInfo.value.UserId,
          mobile: userInfo.value.PhoneNumber,
        });
        break;
    }
  }

  /** 处理修改密码窗体确认按钮 */
  async function handleChangePasswordModalOk(value: any) {
    try {
      const userInfoValue = await identityStore.changePassword({
        OldPassword: value.OldPassword,
        NewPassword: value.NewPassword,
        ConfirmNewPassword: value.ConfirmNewPassword,
        mode: 'none',
      });
      if (userInfoValue !== undefined && userInfoValue !== null) {
        userInfo.value = userInfoValue;
        createMessage.success(t('routes.dashboard.account.setting.submitSuccess'));
        return true;
      }
      return false;
    } catch (error: any) {
      if (error?.message) {
        createMessage.error(error?.message);
      }
      return false;
    }
  }

  /** 处理修改邮箱窗体确认按钮 */
  async function handleChangeEmailModalOk(value: any) {
    try {
      const userInfoValue = await identityStore.changeUserEmail({
        Id: value.Id,
        Email: value.Email,
        EmailConfirmUrl: `${window.location.origin}/#/confirm-email`,
        VerifyCode: value.VerifyCode,
        VerifyCodeId: value.VerifyCodeId,
        mode: 'none',
      });
      if (userInfoValue !== undefined && userInfoValue !== null) {
        createSuccessModal({
          title: () => h('span', t('routes.dashboard.account.setting.submitSuccess')),
          content: () =>
            h('span', t('routes.dashboard.account.setting.activationEmail', [userInfoValue.Email])),
        });
        userInfo.value = userInfoValue;
        return true;
      }
      return false;
    } catch (error: any) {
      if (error?.message) {
        createMessage.error(error?.message);
      }
      return false;
    }
  }

  /** 处理修改手机窗体确认按钮 */
  async function handleChangePhoneModalOk(value: any) {
    try {
      const userInfoValue = await identityStore.changeUserPhone({
        Id: value.Id,
        PhoneNumber: value.PhoneNumber,
        SmsCode: value.SmsCode,
        SmsCodeId: value.SmsCodeId,
        mode: 'none',
      });
      if (userInfoValue !== undefined && userInfoValue !== null) {
        createMessage.success(t('routes.dashboard.account.setting.submitSuccess'));
        userInfo.value = userInfoValue;
        return true;
      }
      return false;
    } catch (error: any) {
      if (error?.message) {
        createMessage.error(error?.message);
      }
      return false;
    }
  }
</script>
